// 收到255.1.0
import { resArr, setDataDecryptController } from '../socketOnMessageTools'
import store from '@/store'
import router from '@/router'
import { sendSock } from '@/utils/socketSend'
import { aesDecrypt } from '@/secret/secret'
import { ifContactInList, decryptMessage } from '../socketTools'
import tools from '@/utils/tools'

// 解析消息
const decryptMsg = decryptMessage
// 判断缓存的用户列表中是否有该用户
const ifContactInContactlist = ifContactInList

const dataDealer = tools.dataDealer

export default async (result) => {
  // 认证成功
  if (store.state.socket.operationReqId.identityReqId === result.reqId) {
    // 认证成功 拉取最近联系人列表
    sendSock({
      type: '5.2.3',
      body: ''
    })
    store.commit('socket/set_operationReqId', 'pullRecentContactsListReqId')
    return
  }
  // 拉取最近联系人列表成功
  if (store.state.socket.operationReqId.pullRecentContactsListReqId === result.reqId) {
    const uintData = aesDecrypt(result.body, store.state.socket.DHSecretKey, true).buffer
    if (uintData.byteLength) {
      setDataDecryptController({
        bodyData: uintData,
        nameArr: ['id', 'id_type', 'timestamp'],
        firstIndex: 0,
        ifMsgArr: true
      })
    }
    const recentContactArr = resArr
    for (let i = 0; i < recentContactArr.length; i++) {
      if (recentContactArr[i].id_type === 1) {
        const userInfo = await store.dispatch('addressList/getUserDetail', recentContactArr[i].id)
        if (userInfo.data && userInfo.data.code === 200) {
          if (userInfo.data.data.exists) {
            recentContactArr[i].in_contact = userInfo.data.data.in_contact
            recentContactArr[i].name = userInfo.data.data.info.remarks ? userInfo.data.data.info.remarks : userInfo.data.data.info.user_name
            recentContactArr[i].messages = []
            recentContactArr[i].draft = ''
            const user = {
              user_name: userInfo.data.data.info.user_name,
              user_img_id: userInfo.data.data.info.user_img,
              in_contact: userInfo.data.data.in_contact,
              remarks: userInfo.data.data.info.remarks,
              user_phone: userInfo.data.data.info.user_phone
            }
            store.commit('chatInformation/add_user', {
              userID: userInfo.data.data.info.user_id,
              userInfo: user
            })
          }
        }
      } else {
        const groupInfo = await store.dispatch('groups/getGroupInfo', recentContactArr[i].id)
        if (groupInfo.data && groupInfo.data.code === 200 && groupInfo.data.data) {
          recentContactArr[i].name = groupInfo.data.data.group_name
          recentContactArr[i].group_sponsor = groupInfo.data.data.group_sponsor
          recentContactArr[i].group_time = groupInfo.data.data.group_time
          recentContactArr[i].messages = []
          recentContactArr[i].draft = ''
          const group = {
            group_name: groupInfo.data.data.group_name,
            group_sponsor: groupInfo.data.data.group_sponsor,
            group_img_id: groupInfo.data.data.group_img
          }
          store.commit('chatInformation/add_group', {
            groupID: groupInfo.data.data.group_id,
            groupInfo: group
          })
        }
      }
    }
    store.commit('chatInformation/replace_contact', recentContactArr)
    // 拉取最近联系人列表成功 拉取未读消息
    sendSock({
      type: '5.2.2',
      body: ''
    })
    store.commit('socket/set_operationReqId', 'pullUnreadMessageReqId')
    return
  }
  // 拉取未读消息成功
  if (store.state.socket.operationReqId.pullUnreadMessageReqId === result.reqId) {
    const uintData = aesDecrypt(result.body, store.state.socket.DHSecretKey, true).buffer
    const count = dataDealer.uint8ToNum(dataDealer.uint8Intercept(uintData, 0, 4), 32)
    if (count) {
      setDataDecryptController({
        bodyData: uintData,
        nameArr: ['msg_type', 'type_msg', 'from', 'timestamp', 'belong', 'send_uint', 'id_length', 'msg_id'],
        firstIndex: 4,
        ifMsgArr: true
      })

      const resultArr = resArr.reverse()

      for (const msg of resultArr) {
        // 如果用户缓存列表中没有该用户
        await ifContactInContactlist(msg.from, 1)
        // 如果用户缓存列表中没有该群组
        if (msg.belong === 2) {
          await ifContactInContactlist(msg.send_uint, 2)
        }
        switch (msg.msg_type) {
          // 文字消息
          case 1: {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: msg.from,
                isSelf: false,
                msg: msg.type_msg.msg,
                msg_id: msg.msg_id,
                type: 'words',
                timestamp: msg.timestamp,
                unread: true
              },
              id: msg.send_uint,
              idType: msg.belong
            })
            break
          }
          // 语音消息
          case 2: {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: msg.from,
                isSelf: false,
                msg_id: msg.msg_id,
                type: 'voice',
                timestamp: msg.timestamp,
                voiceSrc: await store.dispatch('file/downloadFile', {
                  fileType: msg.belong === 1 ? 4 : 5,
                  fileID: msg.type_msg.fileId,
                  other: msg.send_uint
                }),
                voice_id: msg.type_msg.fileId,
                unread: true,
                listened: false
              },
              id: msg.send_uint,
              idType: msg.belong
            })
            break
          }
          // 图片消息
          case 3: {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: msg.from,
                isSelf: false,
                msg_id: msg.msg_id,
                type: 'pic',
                timestamp: msg.timestamp,
                imgSrc: dataDealer.blobToUrl(await store.dispatch('file/downloadFile', {
                  fileType: msg.belong === 1 ? 4 : 5,
                  fileID: msg.type_msg.imgId,
                  other: msg.send_uint
                })),
                img_id: msg.type_msg.imgId,
                img_width: msg.type_msg.imgWidth,
                img_height: msg.type_msg.imgHeight,
                unread: true
              },
              id: msg.send_uint,
              idType: msg.belong
            })
            break
          }
          // 文件消息
          case 4: {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: msg.from,
                isSelf: false,
                msg_id: msg.msg_id,
                type: 'file',
                timestamp: msg.timestamp,
                file_name: msg.type_msg.fileName,
                file_id: msg.type_msg.fileId,
                file_size: msg.type_msg.fileSize,
                unread: true
              },
              id: msg.send_uint,
              idType: msg.belong
            })
            break
          }
          // 视频通话消息
          case 5: {
            if (msg.type_msg.callState === 0) {
              store.commit('message/set_videoCallInfo', {
                isInviter: false,
                oppositeID: msg.from
              })
              store.commit('common/set_ifShowVideoInvitation', true)
              store.commit('message/set_videoCallMsgID', msg.msg_id)
            } else {
              store.dispatch('chatInformation/setAddMessage', {
                message: {
                  id: msg.from,
                  isSelf: false,
                  msg_id: msg.msg_id,
                  type: 'videoCall',
                  timestamp: msg.timestamp,
                  duration: msg.type_msg.duration,
                  callType: msg.type_msg.callType,
                  callState: msg.type_msg.callState
                },
                id: msg.send_uint,
                idType: msg.belong
              })
            }
            break
          }
        }
      }
    }
    return
  }
  // 拉取消息记录成功
  if (store.state.socket.operationReqId.pullHistoryRecordReqId === result.reqId) {
    const uintData = aesDecrypt(result.body, store.state.socket.DHSecretKey, true).buffer

    const total = Number(dataDealer.uint8ToNum(dataDealer.uint8Intercept(uintData, 0, 8), 64))
    const count = dataDealer.uint8ToNum(dataDealer.uint8Intercept(uintData, 8, 4), 32)

    if (total && count) {
      setDataDecryptController({
        bodyData: uintData,
        nameArr: ['msg_type', 'type_msg', 'from', 'timestamp', 'id_length', 'msg_id'],
        firstIndex: 12,
        ifMsgArr: true
      })
      const resultArr = resArr
      for (const msg of resultArr) {
        switch (msg.msg_type) {
          // 文本消息
          case 1: {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: msg.from,
                isSelf: tools.isSelf(msg.from),
                msg: msg.type_msg.msg,
                msg_id: msg.msg_id,
                type: 'words',
                timestamp: msg.timestamp,
                unread: false
              },
              id: store.state.chatInformation.current_contact.id,
              idType: store.state.chatInformation.current_contact.id_type,
              ifFront: true
            })
            break
          }
          // 语音消息
          case 2: {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: msg.from,
                isSelf: tools.isSelf(msg.from),
                msg_id: msg.msg_id,
                type: 'voice',
                timestamp: msg.timestamp,
                voiceSrc: await store.dispatch('file/downloadFile', {
                  fileType: store.state.chatInformation.current_contact.id_type === 1 ? 4 : 5,
                  fileID: msg.type_msg.file_id,
                  other: store.state.chatInformation.current_contact.id
                }),
                voice_id: msg.type_msg.fileId,
                unread: false,
                listened: true
              },
              id: msg.from,
              idType: store.state.chatInformation.current_contact.id_type,
              ifFront: true
            })
            break
          }
          // 图片消息
          case 3: {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: msg.from,
                isSelf: tools.isSelf(msg.from),
                msg_id: msg.msg_id,
                type: 'pic',
                timestamp: msg.timestamp,
                imgSrc: dataDealer.blobToUrl(await store.dispatch('file/downloadFile', {
                  fileType: store.state.chatInformation.current_contact.id_type === 1 ? 4 : 5,
                  fileID: msg.type_msg.imgId,
                  other: store.state.chatInformation.current_contact.id
                })),
                img_id: msg.type_msg.imgId,
                img_width: msg.type_msg.imgWidth,
                img_height: msg.type_msg.imgHeight
              },
              id: store.state.chatInformation.current_contact.id,
              idType: store.state.chatInformation.current_contact.id_type,
              ifFront: true
            })
            break
          }
          // 文件消息
          case 4: {
            store.dispatch('chatInformation/setAddMessage', {
              message: {
                id: msg.from,
                isSelf: tools.isSelf(msg.from),
                msg_id: msg.msg_id,
                type: 'file',
                timestamp: msg.timestamp,
                file_name: msg.type_msg.fileName,
                file_id: msg.type_msg.fileId,
                file_size: msg.type_msg.fileSize
              },
              id: store.state.chatInformation.current_contact.id,
              idType: store.state.chatInformation.current_contact.id_type,
              ifFront: true
            })
            break
          }
          // 视频通话消息
          case 5: {
            // 判断是否有正在打的电话
            if (msg.type_msg.callState === 0) {
              store.commit('message/set_videoCallInfo', {
                isInviter: false,
                oppositeID: msg.from
              })
            } else {
              store.dispatch('chatInformation/setAddMessage', {
                message: {
                  id: msg.from,
                  isSelf: tools.isSelf(msg.from),
                  msg_id: msg.msg_id,
                  type: 'videoCall',
                  timestamp: msg.timestamp,
                  duration: msg.type_msg.duration,
                  callType: msg.type_msg.callType,
                  callState: msg.type_msg.callState
                },
                id: store.state.chatInformation.current_contact.id,
                idType: store.state.chatInformation.current_contact.id_type,
                ifFront: true
              })
            }
          }
        }
      }
    }
    return
  }
  // 发送消息成功
  if (store.state.socket.operationReqId.sendMessageId === result.reqId) {
    decryptMsg(result.body, ['msg_id'], 0)
    const realData = resArr[0]
    const chatInformation = store.state.chatInformation.chatInformation
    for (let i = 0; i < chatInformation.length; i++) {
      if (chatInformation[i].messages[chatInformation[i].messages.length - 1] && chatInformation[i].messages[chatInformation[i].messages.length - 1].reqId) {
        if (chatInformation[i].messages[chatInformation[i].messages.length - 1].reqId === result.reqId) {
          store.commit('chatInformation/supplement_msgId', {
            id: chatInformation[i].id,
            idType: chatInformation[i].id_type,
            msgID: realData.msg_id
          })
          break
        }
      }
    }
    return
  }
  // 撤回消息成功
  if (store.state.socket.operationReqId.withdrawReqId === result.reqId) {
    // 撤回消息
    store.commit('chatInformation/withdrawMsg', store.state.message.withdrawInfo)
    // 清空撤回对象
    store.commit('message/set_withdrawInfo', {})
    return
  }
  // 加入会议成功
  if (store.state.socket.operationReqId.joinConferenceReqId === result.reqId) {
    decryptMsg(result.body, ['cf_id', 'cf_code', 'cf_name_length', 'cf_name', 'cf_host', 'cf_sponsor', 'cf_start_time', 'cf_isLocked', 'cf_mute_all', 'cf_close_camera_all', 'cf_member_length', 'cf_members', 'cf_invited'], 0)
    const realData = resArr[0]

    realData.cf_members.forEach(item => {
      ifContactInContactlist(item.id, 1)
      item.stream = new MediaStream()
    })
    for (const key in realData) {
      store.commit('conferenceRoom/set_attribute', {
        attributeKey: key,
        attributeValue: realData[key]
      })
    }
    // 判断当前会议是否开启了入会密码
    if (tools.conference.isHost(tools.getUserId())) {
      store.commit('conferenceRoom/set_cf_need_password', Boolean(store.state.conferenceRoom.cf_password))
    }
    router.push('/conferenceRoom')
    tools.webRTC.openMedia({}).then(stream => {
      // 如果入会不开启摄像头
      if (!store.state.conferenceRoom.conferenceSettings.camera) {
        tools.webRTC.closeCamera(stream)
      }
      // 如果入会不开启麦克风
      if (!store.state.conferenceRoom.conferenceSettings.voiced) {
        tools.webRTC.muteMicPhone()
      }
      // 如果主持人开启了静音所有人
      if (store.state.conferenceRoom.cf_mute_all && !tools.conference.isHost(store.state.user.userInfo.user_id)) {
        tools.webRTC.muteMicPhone()
      }
    })
    return
  }
  // 发起视频通话成功
  if (store.state.socket.operationReqId.sendCallReqId === result.reqId) {
    decryptMsg(result.body, ['msg_id'], 0)
    const realData = resArr[0]
    // 视频通话邀请发送成功 存储msgID 显示对方信息拨打框
    store.commit('message/set_videoCallMsgID', realData.msg_id)
    store.commit('message/set_videoCallInfo', {
      isInviter: true,
      oppositeID: store.state.chatInformation.current_contact.id
    })
    store.commit('common/set_ifShowVideoInvitation', true)
    return
  }
  // 取消视频通话成功
  if (store.state.socket.operationReqId.cancelVideoCallId === result.reqId) {
    store.dispatch('chatInformation/setAddMessage', {
      message: {
        isSelf: true,
        type: 'videoCall',
        timestamp: +new Date(),
        callState: 1
      },
      id: store.state.message.videoCallInfo.oppositeID,
      idType: 1
    })
    store.commit('chatInformation/supplement_msgId', {
      id: store.state.message.videoCallInfo.oppositeID,
      idType: 1,
      msgID: store.state.message.videoCallMsgID
    })
    store.commit('chatInformation/set_topContact', {
      id: store.state.message.videoCallInfo.oppositeID,
      id_type: 1
    })
    store.commit('message/set_videoCallInfo', {
      isInviter: null,
      oppositeID: null
    })
    store.commit('common/set_ifShowVideoInvitation', false)
    store.commit('message/set_videoCallMsgID', null)
    return
  }
  // 拒绝视频通话成功
  if (store.state.socket.operationReqId.refuseVideoCallId === result.reqId) {
    store.dispatch('chatInformation/setAddMessage', {
      message: {
        id: store.state.message.videoCallInfo.oppositeID,
        isSelf: false,
        type: 'videoCall',
        timestamp: +new Date(),
        callState: 2
      },
      id: store.state.message.videoCallInfo.oppositeID,
      idType: 1
    })
    store.commit('chatInformation/supplement_msgId', {
      id: store.state.message.videoCallInfo.oppositeID,
      idType: 1,
      msgID: store.state.message.videoCallMsgID
    })
    store.commit('chatInformation/set_topContact', {
      id: store.state.message.videoCallInfo.oppositeID,
      id_type: 1
    })
    store.commit('message/set_videoCallInfo', {
      isInviter: null,
      oppositeID: null
    })
    store.commit('common/set_ifShowVideoInvitation', false)
    store.commit('message/set_videoCallMsgID', null)
    return
  }
  // 接受视频通话成功
  if (store.state.socket.operationReqId.acceptVideoCallId === result.reqId) {
    // 将该视频通话的msg_id作为房间ID用来防止路由随意跳转
    store.commit('conferenceRoom/set_cf_id', store.state.message.videoCallMsgID)
    // 将房间类型设置为videoCall
    store.commit('conferenceRoom/set_cf_type', 'videoCall')
    // 将房间设置自动配置 摄像头必开
    store.commit('conferenceRoom/set_conferenceSettings', {
      voiced: true,
      camera: true,
      durationOfAttendance: true
    })
    // 房间用户设置
    store.commit('conferenceRoom/set_cf_members', [
      {
        id: tools.getUserId(),
        voiced: true,
        camera: true,
        stream: new MediaStream()
      },
      {
        id: store.state.message.videoCallInfo.oppositeID,
        voiced: true,
        camera: true,
        stream: new MediaStream()
      }
    ])
    // 设置通话开始时间
    store.commit('conferenceRoom/set_cf_start_time', +new Date())
    // 跳转路由
    router.push('/videoCall')
    const oppositeUser = JSON.parse(JSON.stringify(store.state.message.videoCallInfo))
    // 打开摄像头
    tools.webRTC.openMedia({}).then(stream => {
      // 与对方建立peerConnection

      tools.webRTC.getPeerConnection(oppositeUser.oppositeID).then(peer => {
        tools.webRTC.addTracks(peer, stream)
      })
    })
    store.commit('common/set_ifShowVideoInvitation', false)
    store.commit('message/set_videoCallMsgID', null)
    return
  }
  // 通话关闭摄像头成功
  if (store.state.socket.operationReqId.closeCameraReqId === result.reqId) {
    tools.webRTC.closeCamera()
    store.commit('conferenceRoom/set_conferenceSettings_camera', false)
    store.commit('conferenceRoom/set_cf_member_device', {
      id: tools.getUserId(),
      type: 'camera',
      status: false
    })
    return
  }
  // 通话打开摄像头成功
  if (store.state.socket.operationReqId.openCameraReqId === result.reqId) {
    tools.webRTC.openCamera()
    store.commit('conferenceRoom/set_conferenceSettings_camera', true)
    store.commit('conferenceRoom/set_cf_member_device', {
      id: tools.getUserId(),
      type: 'camera',
      status: true
    })
  }
}
